package mgodb

import (
	"github.com/facebookgo/inject"
	"github.com/globalsign/mgo"
	"github.com/globalsign/mgo/bson"
	"github.com/pkg/errors"
	"jgt-oper/src/model"
	"jgt-oper/src/schema"
	"jgt-oper/src/service/mongo"
)

// cEnterpriseParkHistory 门牌历史表
const cEnterpriseParkHistory = "oper_park_history"

// EnterHistory 门牌历史
type EnterHistory struct {
	DB *mongo.DB
}

// Init 初始化
func (a *EnterHistory) Init(g *inject.Graph, db *mongo.DB) {
	a.DB = db
	//此处不需要进行初始化索引，因为此表cEnterprise的索引已经初始化过（在企业管理功能模块里初始化过）
	a.DB.C(cEnterpriseParkHistory, func(c *mgo.Collection) error {
		c.EnsureIndex(mgo.Index{
			Key:    []string{"_id"},
			Unique: true,
		})
		c.EnsureIndexKey("_id")
		return nil
	})
	var val model.IEnterHistory = a
	g.Provide(&inject.Object{Value: val, Name: "IEnterHistory"})
}

// QueryPage 查询分页
func (a *EnterHistory) QueryPage(params *schema.EnterHistoryQueryParam) (interface{}, interface{}, error) {
	//查询统计对应条件的总数
	query := bson.M{
		"park_id": bson.M{"$regex": params.BuildingNodeID},
	}
	//管道查询条件
	pipeArrayOper := []bson.M{
		{"$match": bson.M{"park_id": bson.M{"$regex": params.BuildingNodeID},
			"$and": []bson.M{{"created": bson.M{"$gte": params.StartTime}}, {"created": bson.M{"$lte": params.EndTime}}}}},
		{"$lookup": bson.M{"from": "oper_user", "localField": "creator", "foreignField": "record_id", "as": "oper_user"}},
		{"$lookup": bson.M{"from": "oper_enterprise", "localField": "enterprise_id", "foreignField": "record_id", "as": "oper_enterprise"}},
		{"$lookup": bson.M{"from": "oper_park", "localField": "park_id", "foreignField": "record_id", "as": "oper_park"}},
		{"$unwind": bson.M{"path": "$oper_user", "preserveNullAndEmptyArrays": true}},
		{"$unwind": bson.M{"path": "$oper_enterprise", "preserveNullAndEmptyArrays": true}},
		{"$unwind": bson.M{"path": "$oper_park", "preserveNullAndEmptyArrays": true}},
		{"$addFields": bson.M{"user_name": "$oper_user.real_name", "enterprise_name": "$oper_enterprise.name", "park_node_name": "$oper_park.name"}},
		{"$project": bson.M{"oper_user": 0, "oper_enterprise": 0, "oper_park": 0}},
		{"$sort": bson.M{"created": -1}},
		{"$skip": (params.PageIndex - 1) * params.PageSize},
		{"$limit": params.PageSize},
	}
	var total int64
	var items []*schema.ResultOfParkHistory
	err := a.DB.C(cEnterpriseParkHistory, func(c *mgo.Collection) error {
		n, err := c.Find(query).Count()
		if err != nil {
			return err
		}
		total = int64(n)
		if total == 0 {
			return nil
		}
		return c.Pipe(pipeArrayOper).All(&items)
	})
	if err != nil {
		return 0, nil, errors.Wrapf(err, "查询分页数据发生错误")
	}

	return total, items, nil
}

// InsertItem 插入门牌历史条目
func (a *EnterHistory) InsertItem(item *schema.EnterpriseParkHistory) error {
	err := a.DB.C(cEnterpriseParkHistory, func(c *mgo.Collection) error {
		id, err := a.DB.IncrID(cEnterpriseParkHistory)
		if err != nil {
			return errors.Wrapf(err, "门牌历史表，插入数据条目的ID 创建出错！")
		}
		item.ID = id
		return c.Insert(item)
	})
	if err != nil {
		return errors.Wrapf(err, "门牌历史表，创建记录数据发生错误！")
	}
	return nil
}
